package com.fubowen.reader.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.fubowen.reader.R
import com.fubowen.reader.adapter.SimpleListAdapter
import com.fubowen.reader.databinding.FragmentReaderBookshelfBinding
import com.fubowen.reader.db.database
import com.fubowen.reader.db.model.Bookshelf
import com.fubowen.reader.db.model.toBookshelf
import kotlinx.coroutines.launch

class BookshelfFragment : Fragment() {

    private lateinit var binding: FragmentReaderBookshelfBinding

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        super.onCreateView(inflater, container, savedInstanceState)
        binding = FragmentReaderBookshelfBinding.inflate(inflater, container, false)
        initRecyclerView()
        binding.bookshelfHistory.setOnClickListener {
            val action = BookshelfFragmentDirections.actionBookshelfFragmentToImportBookFragment()
            findNavController().navigate(action)
        }
        return binding.root
    }

    //region initRecyclerView
    private fun initRecyclerView() {
        val recycler = binding.bookshelfRecycler
        val layoutManager = LinearLayoutManager(requireContext())
        val adapter = SimpleListAdapter<Bookshelf>(R.layout.fragment_reader_bookshelf_item, requireContext()) {
//            val position = layoutManager.getPosition(view.root)
//            val item = adapter.currentList[position]
//            val book = item.book
//            if (book != null) {
//                openBook(book)
//            }
        }
        recycler.layoutManager = layoutManager
        recycler.adapter = adapter
        lifecycleScope.launch {
            requireContext().database.bookDao().allFlow().collect {
                adapter.submitList(it.toBookshelf())
            }
        }
    }
    //endregion

    //region openBook
//    private fun openBook(book: Book) {
//        val action = BookshelfFragmentDirections.actionBookshelfFragmentToReaderFragment2(book.id)
//        controller.navigate(action)
//    }
    //endregion
}